import moment from 'moment';
import CryptoJS from 'crypto-js';
import environment from "@/environment"
import { defer, concatMap, forkJoin, map, of } from "rxjs";

function formatFileSize(size) {
  return (size / (1024 * 1024)).toFixed(1) + "M";
}

function formatDuration({ duration, unit, format }) {
  return moment
    .duration(duration, unit || 'milliseconds')

    // @ts-ignore
    .format(format || 'mm:ss', { trim: false });
}

function getRandomItemFromArray(array) {
  if (array.length <= 0) return undefined;
  return array[Math.floor(array.length * Math.random())];
}

function uuid(length = 30, prefix = '') {
  let guid = '';
  for (let i = 1; i <= length; i++) {
    let n = Math.floor(Math.random() * 16.0).toString(16);
    guid += n;
  }
  return `${prefix ? `${prefix}-` : ''}${guid}`;
}

export function encrypt(d) {
  return CryptoJS.AES.encrypt(
    JSON.stringify(d),
    environment.encryptKey,
  ).toString();
}

export function decrypt(t, parse = false) {
  try {
    const bytes = CryptoJS.AES.decrypt(
      t,
      environment.encryptKey,
    );
    const text = bytes.toString(CryptoJS.enc.Utf8);
    return parse ? JSON.parse(text) : text;
  } catch (error) { }
  return undefined;
}

function md5(d) {
  return CryptoJS.MD5(d.toString()).toString();
}

function formatSingerName(song) {
  return (song.singer || []).map(e => e.name).join("、");
}

function formatSongDuration(duration) {
  return moment.duration(duration || 0, 'seconds').format('mm:ss', { trim: false });
}

function getArray(length = 10) {
  return Array.from(new Array(length).keys());
}

function equalString(a, b) {
  return `${a}` === `${b}`;
}

function clone(_) {
  return JSON.parse(JSON.stringify(_));
}

const $helper = {
  uuid, getRandomItemFromArray, formatDuration, encrypt, decrypt,
  md5, formatSongDuration, formatSingerName, getArray, equalString,
  clone, formatFileSize,
};

export default $helper;